<?php
/**
 * Created by PhpStorm.
 * User: khq
 * Date: 16-12-29
 * Time: 下午3:43
 */
namespace Inbound\Model;
use Inbound\Model\PrepareneedsModel;
use Inbound\Service\PublicInfoService;
use Think\Exception;

class PrepareneedsdetailModel extends CommoninterfaceModel{

    public $obj              = NULL;
    //备货需求明细表
    static $table           = 'fba_prepare_needs_details';
    //数据库对象
    public $prepareNeedsDetails = NULL;
    //数据
    public $data             = array();
    //需求明细明细数据
    public $prepare_needs_detail = array();

    public $prepare_needs_detail_id = '';

    /**
     * PrepareneedsdetailModel constructor.
     * @param string $table
     * @param array $param
     */
    public function __construct($table = '',$param=array()){
        $this->prepareNeedsDetails = M(self::$table,' ',$this->_db);
        parent::__construct();
    }
    public function select_detail(&$_array = array(),$flag = TRUE){

    }

    /**
     * @param $info
     * @return mixed
     * 根据帐号名、SKU、要求到货时间在别的状态为10的批次号里是否有重复的需求
     */
    public function batchCodeSelect($info)
    {
        $map = array(
            'd.batch_code'        => array('neq',$info['batch_code']),
            'd.account_name'      => array('eq' ,$info['account_name']),
            'd.sku'               => array('eq' ,$info['sku']),
            'd.claim_arrive_time' => array('eq' ,$info['claim_arrive_time']),
            'd.status'            => array('eq' ,10),
            'm.status'            => array('eq' ,10)
        );

        return $this->prepareNeedsDetails
            ->table($this->_db.'.'.self::$table.' d')
            ->join('LEFT JOIN '.$this->_db.'.fba_prepare_needs m on d.prepare_needs_id=m.id')
            ->where($map)
            ->select();
    }

    /**
     * @return mixed
     */
    public function canChangeCodeSelect()
    {
        return M('fba_prepare_needs', ' ', $this->_db)
            ->where(array('status' => 10))
            ->getField('batch_code', true);
    }

    /**
     * @param $info
     * @param $targetCode
     * @return mixed
     */
    public function batchCodeUpdate($ids, $org_code, $targetCode)
    {
        $may['id'] = array('IN', $ids);
        $num = $this->prepareNeedsDetails->where($may)->save(array('batch_code' => $targetCode));

        foreach ($org_code as $code) {
            $orgCodeStatus = $this->prepareNeedsDetails->where(
                array(
                    'batch_code' => $code,
                    'status'     => 10
                )
            )->select();
            /*如果原始批次内的备货SKU的状态都不为10了，则该批次的状态也更新为20*/
            if (!$orgCodeStatus) {
                M('fba_prepare_needs', ' ', $this->_db)->where(array(
                    'batch_code' => $code,
                    'status'      => 10
                    )
                )->save(array('status' => 20));
            }
        }

        return $num;
    }

    /**
     * @param $stockingDetail
     * @return int
     * 描述：更新备货需求状态，包括是否是单独发货
     */
    public function logisticsPreview($stockingDetail) {
        $num = 0;
        foreach ($stockingDetail as $detail) {
            $map['id'] = $detail['id'];
            $map['status'] = 20;

            $num += $this->prepareNeedsDetails
                ->where($map)
                ->save(array(
                    'status' => 30,
                    'single_ship' => $detail['single_ship'],
                    'logistic_check_user_id' => $_SESSION['current_account']['id'],
                    'logistic_check_time' => date("Y-m-d H:i:s")
                    ));
        }
        return $num ? $num : 0;
    }

    public function compliancePreview($complianceData) {
        $num = 0;
        foreach ($complianceData as $data) {
            $map['id'] = $data['id'];
            $map['status'] = 15;

            $num += $this->prepareNeedsDetails
                ->where($map)
                ->save(array(
                    'status' => 20,
                    'compliance' => $data['compliance']?$data['compliance']:'',
                    'compliance_check_user_id' => $_SESSION['current_account']['id'],
                    'compliance_check_time' => date("Y-m-d H:i:s")
                ));

            $site_id = PublicInfoService::get_site_id($data['site_id']);

            if (!$data['compliance']) {
                M('fba_prepare_needs_sku_compliance', ' ', $this->_db)
                    ->where(array(
                        'site_id' => $site_id,
                        'sku' => $data['sku']
                    ))->delete();
            } else {
                $sql = "INSERT INTO `fba_prepare_needs_sku_compliance`( `site_id`, `sku`, `compliance`, `comment`)
                        VALUES ({$site_id},'{$data['sku']}','{$data['compliance']}','{$data['comment']}')
                        ON DUPLICATE KEY UPDATE `compliance` = '{$data['compliance']}'";

                M('fba_prepare_needs_sku_compliance', ' ', $this->_db)
                    ->query($sql);
            }

        }
        return $num ? $num : 0;
    }

    public function getComplianceInfo($array) {
        return $this->prepareNeedsDetails->table($this->_db . '.' . self::$table)
            ->table($this->prepareneedsdetail->_db . '.fba_prepare_needs_details AS fpnd')
            ->join("LEFT JOIN fba_prepare_needs_sku_compliance AS fpnsc ON fpnsc.sku = fpnd.sku")
            ->join("LEFT JOIN skusystem_sku_cnname AS ssc ON fpnd.sku = ssc.sku")
            ->join("LEFT JOIN skusystem_cnname AS sc ON ssc.attr_id = sc.id")
            ->join("LEFT JOIN amazonorder_sites AS site ON site.id = fpnd.site_id")
            ->join("LEFT JOIN amazonadmin.ea_admin as ea ON ea.id = fpnd.buyer_id")
            ->field("fpnd.compliance_check_time,fpnd.sku,sc.name,site.shorthand_code,ea.remark,fpnsc.compliance,fpnsc.comment")
            ->where($array)
            ->order("fpnd.compliance_check_time")
            ->select();
    }

    /**
     * @param $id
     * @return mixed
     * 根据明细id获取明细的数据
     */
    public function get_data_by_id($id){
        return $this->prepareNeedsDetails
            ->where(array('id'=>$id))
            ->select();
    }

    /**
     * @param $id
     * @param $batch_code
     * @return mixed
     * 获取备货批次中指定id之外的所有明细状态
     */
    public function get_status_by_code($id,$batch_code){
        $map['id'] = array('not in',$id);
        return $this->prepareNeedsDetails
            ->where(array('batch_code'=>$batch_code))
            ->where($map)
            ->field('status')
            ->select();
    }

    /**
     * @param $ids
     * @return mixed
     * 获取备货需求明细的状态
     */
    public function get_prepare_details_status($ids,$status){
        $map = array(
            'id'     => array('in',$ids),
            'status' => array('neq',$status)
        );
        return $this->prepareNeedsDetails
            ->where($map)
            ->getField('id,status');
    }
    /**
     * 检查备货需求主表是否符合当前审核条件
     * kqh 2017.1.15
     */
    public function check_prepare_status($ids,$status){
        $map = array(
            'd.id'     => array('in',$ids),
            'm.status' => array('neq',$status)
        );
        return $this->prepareNeedsDetails
            ->table($this->_db.'.'.self::$table.' d')
            ->join('LEFT JOIN '.$this->_db.'.fba_prepare_needs m on d.prepare_needs_id=m.id')
            ->field('d.id,m.status')
            ->where($map)
            ->select();
    }

    /**
     * @param $ids
     * @return mixed
     * 获取备货明细的数据
     */
    public function get_prepare_details($ids){
        $map = array(
            'id'     => array('in',$ids),
        );
        return $this->prepareNeedsDetails
            ->where($map)
            ->select();
    }

    /**
     * @param $ids
     * @return mixed
     * 获取明细中最小的到货日期
     */
    public function get_min_date($ids)
    {
        $map = array(
            'id'     => array('in',$ids),
        );
        return $this->prepareNeedsDetails
            ->where($map)
            ->getField("min(claim_arrive_time)");
    }

    /**
     * @param $map
     * @return mixed
     * 通过批次号+账号+站点+sku+是否退税
     * 查出明细对应sku
     */
    public function get_prepare_detail_id($map)
    {
        $_param['status'] = array('neq',100);
        return $this->prepareNeedsDetails
            ->where($map)
            ->where($_param)
            ->getField('id');
    }
    /**
     * @param array $_array -备货需求明细
     * @return mixed
     * 批量创建备货需求明细
     * khq 2016.12.31
     */
    public function batch_create(&$_array = array())
    {
        return parent::batch_create($_array, $this->model->table("$this->_db.".self::$table)); // TODO: 
    }

    public function update($_array, $_param, &$model = NULL)
    {
        return parent::update($_array, $_param, $this->model->table("$this->_db.".self::$table)); // TODO:
    }
    /**
     * @param $id
     * @param $batch_code
     * @return mixed
     * 检查批次里面所有需求是否全部已完成或取消
     */
    public function checkBateCodeAllStatus($batch_code)
    {
        return $this->prepareNeedsDetails
            ->where(array('batch_code'=>$batch_code))
            ->where("status NOT IN (100,80)")
            ->field('status')
            ->select();
    }
}